// featurePackage/pages/knowledgeArea/knowledgeArea.js
const app = getApp()
import {
  queryArticleList,
  queryHotArticleList,
  articleCategoryList,
  articleBannerList,
} from "../../../service/jb_article_service"
import {
  BIND_USER_ID,
  VIDEO_COVER,
} from "../../../service/base_service"
import {
  addCollect,
  cancelCollect,
} from "../../../service/jb_common_service"
import {
  loginWxAction
} from "../../../service/config"
import {
  querGlobalConfig
} from "../../../service/jb_home_service"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoCoverUrl: VIDEO_COVER,
    topSwiper: [
      // {
      //   image: 'https://mmbiz.qpic.cn/mmbiz_jpg/1rqkHu5x3oRYhSeyqOJW5A54XnsibSkiajKR6I47uRpgoO9vfqCLXlC9ibbqVcsfUmabViaWSVIJjRVwru33oO7iaVw/0?wx_fmt=jpeg',
      //   url: '/example/list/index',
      //   title: 'MEET UI，重新定义用户界面、用户交互、用户体验。'
      // },
      // {
      //   image: 'https://mmbiz.qpic.cn/mmbiz_jpg/1rqkHu5x3oRYhSeyqOJW5A54XnsibSkiajS3iceE9NYiaX2tRVHpMibYr1bZvWiaYiadMiaXPwVQtiaeGk0NViahaicHFXTDw/0?wx_fmt=jpeg',
      //   url: '/example/list/index',
      //   title: 'MEET UI，做对产品、业务真正有帮助的“实用”技术研发！'
      // },
      // {
      //   image: 'https://mmbiz.qpic.cn/mmbiz_jpg/1rqkHu5x3oRYhSeyqOJW5A54XnsibSkiajP6Ekc4SiajBXzb9nC7wdAz8iaWWiagwDAMVJ815h3ltHR7MOBz4yziaCGQ/0?wx_fmt=jpeg',
      //   url: '/example/list/index',
      //   title: 'MEET UI，重新定义用户界面、用户交互、用户体验。'
      // }
    ],
    navBarHeight: app.globalData.menuButton.top + app.globalData.menuButton.height,
    topTypeIndex: 0,//0:文章，1:视频
    secondTags: [

    ],
    dataList: [

    ],
    page: 1,
    limit: 10,
    isShowLoading: false,//加载状态出现
    isBottomShow: false,//是否没有更多数据了
    refreshFlag: false,
    cid: "",//分类id
    videoCategoryList: [],//视频分类
    articleCategoryList: [],//文章分类
    isShareEnter: false,
    isOpen: true,//是否hide video
    isFirstEnter: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.querGlobalConfig();
    if (options.isShare == 1) {
      this.setData({
        isShareEnter: true,
      })
      if (options.userId) {
        wx.setStorageSync(BIND_USER_ID, options.userId);
      }
      this.userWxLogin();
    } else {
      this.queryArticleList('refresh');
      this.articleCategoryList('article')
      this.articleBannerList()
    }

    // 绑定分享参数
    wx.onCopyUrl(() => {
      return { query: `userId=${app.globalData.userId}&isShare=1` }
    })

  },
  onHide() {
    wx.offCopyUrl()
  },
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickname || "";
        app.globalData.avatar = data.avatar || "";
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.userId = data.uid;
        this.queryArticleList('refresh');
        this.articleCategoryList('article')
        this.articleBannerList()
      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);

    })
  },
  querGlobalConfig() {
    querGlobalConfig().then(res => {
      if (res.code == 200) {
        this.setData({
          isOpen: res.data.isShow
        })
      }
    }).catch(err => {
      console.error("JJLog:querGlobalConfig", err);
    })
  },
  swiperTabChange(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      topTypeIndex: index,
      page: 1,
      isBottomShow: false,
      cid: "",
      dataList: [],
    })

    if (index == 0) {
      this.setData({
        cid: "",
        secondTags: this.data.articleCategoryList,
      })
    }
    if (index == 1 && this.data.videoCategoryList.length > 0) {
      this.setData({
        cid: "",
        secondTags: this.data.videoCategoryList,
      })
    }
    this.queryArticleList('refresh');
    if (index == 1 && this.data.videoCategoryList.length < 1) {
      this.articleCategoryList('video')
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  queryArticleList(type) {
    wx.showLoading();
    let typeIndex = this.data.topTypeIndex == 0 ? 0 : 1;
    queryArticleList(typeIndex, this.data.page, this.data.limit, this.data.cid).then(res => {
      wx.hideLoading();
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.dataList || []);
        arr = arr.concat(res.data.list || [])
        if (this.data.topTypeIndex == 1 && !this.data.isOpen) {
          //只有为视频且这个状态为关闭的时候
          arr = [];
        }
        this.setData({
          //视频数据
          //  {
          //   "id": 2,
          //   "title": "测试知识视频",
          //   "author": "蒋俊",
          //   "imageInput": "https://images.jiabao19.com/images/product/2024-02-17/1708162056588/testVideo.mp4",
          //   "synopsis": "这是一个介绍化妆品的视频啦啦啦啦啦",
          //   "visit": "0",
          //   "content": "视频",
          //   "createTime": "2024-02-18"
          // },
          // dataList: [{
          //   "id": 1,
          //   "title": "论心",
          //   "author": "李先生",
          //   "imageInput": "https://images.jiabao19.com/images/public/maintain/2023/10/18/8d81c840b93d4f7c9ab3c9f78509f152c7i3t24zb3.png",
          //   "synopsis": "迎上去，你将变得不一样",
          //   "visit": "0",
          //   "content": "<p>等闲识得东风面，万紫千红总是春。又一年辞旧迎新，又一次春去冬来。李白说过：&ldquo;<span id=\"body_1_0\">夫天地者，</span><span id=\"body_1_1\">万物之逆旅也；</span><span id=\"body_1_2\">光阴者，</span><span id=\"body_1_3\">百代之过客也。</span><span id=\"body_1_4\">而浮生若梦，</span><span id=\"body_1_5\">为欢几何？</span>&rdquo;</p>\n<p>时光飞逝中，我们满怀期待，再一次迎接春天，迎接花红柳绿，草长莺飞，我们都心有所向，意有所念。</p>\n<p>青春不是一种状态，而是一种心态，只要锐意进取、积极上进、充满好奇，不怕失败，我们就永远年轻。</p>\n<p>虽然人生旅程并没有改变，山还是那座山，水依旧是那道水，但态度不同，心境不同，体验也因此不同。</p>\n<p>迎上去，管他是逆境还是顺境，迎上去，我们才有机会见证未来，迎上去，才会有不一样得自己。</p>\n<p>只要迎上去，我坚信有一天我们一定会感谢那个在寒冷冬天紧握双拳的自己。我坚信，只要迎上去，一定会有一个明媚的春天在你内心绽放。</p>\n<p>总之，我的春天，看我的。</p>\n<p><img class=\"wscnph\" src=\"https://images.jiabao19.com/images/product/2024-02-13/1707833830223/20230715140626.jpg\" /></p>",
          //   "createTime": "2024-02-13"
          // },],
          dataList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.page ? true : false,
        })
      }
    }).catch(err => {
      wx.hideLoading();

      wx.showToast({
        title: err || '加载失败',
        icon: "none"
      })
      if (this.data.page != 1) {
        this.setData({
          page: this.data.page - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
      console.error("JJLog:queryCouponList", err);
    })
  },
  articleCategoryList(type) {
    let extra = type == 'video' ? '视频' : '文章'
    articleCategoryList(extra).then(res => {
      if (res.code == 200) {
        let list = res.data.list || [];
        list.unshift({
          id: '',
          name: "全部类型"
        })
        if (type == 'video') {
          this.setData({
            videoCategoryList: list,
            secondTags: list,
          })
        } else {
          this.setData({
            articleCategoryList: list,
            secondTags: list
          })
        }
      }
    }).catch(err => {

    })
  },

  //下拉刷新
  handleRefresh() {
    this.setData({
      page: 1,
      isBottomShow: false,
      refreshFlag: true,
    })
    this.queryArticleList('refresh');
  },
  //加载更多
  handleLoadmore() {
    console.log('加载更多');
    if (this.data.isBottomShow) {
      return;
    }
    this.setData({
      isShowLoading: true,
      page: this.data.page + 1
    })
    this.queryArticleList()
  },

  articleBannerList() {
    articleBannerList().then(res => {
      if (res.code == 200) {
        let list = res.data.list || []

        if (list.length > 0) {
          let swiperArr = [];
          list.forEach(i => {
            let endArr = i.imageInput.split('.');
            let endStr = endArr[endArr.length - 1];
            if (['mp4', 'wmv', 'avi', 'rmvb', 'mkv'].includes(endStr)) {
              swiperArr.push({
                image: i.imageInput + this.data.videoCoverUrl,
                url: '/pages/videoPlay/videoPlay?id=' + i.id,
                title: i.title || ""
              })
            } else {
              swiperArr.push({
                image: i.imageInput,
                url: '/pages/richPage/richPage?id=' + i.id,
                title: i.title || ""
              })
            }
          })
          this.setData({
            topSwiper: swiperArr
          })
          // console.log("JJLog:规整出来的banner是：" + JSON.stringify(swiperArr));
        }
      }
    }).catch(err => {

    })
  },
  //切换类型
  changeTagAction(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      cid: id ? id : "",
      page: 1,
      isBottomShow: false,
    })
    this.queryArticleList('refresh');
  },

  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  //收藏操作：
  collectAction(e) {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    let knoData = e.detail.data;
    let index = e.detail.index;
    if (!knoData.isCollect) {
      //加入收藏
      this.handlerAddCollect(knoData, index);
    } else {
      this.handlerCancelCollect(knoData, index);
    }

  },

  //加入收藏
  handlerAddCollect(knoData, index) {
    wx.showLoading();
    addCollect({
      category: "article",
      id: knoData.id
    }).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        knoData.collect = knoData.collect + 1
        knoData.isCollect = true;
        let item = 'dataList[' + index + ']';
        this.setData({
          [item]: knoData,
        })
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '收藏失败',
        icon: "none"
      })
    })
  },
  //取消收藏
  handlerCancelCollect(knoData, index) {
    wx.showLoading();
    cancelCollect({
      category: "article",
      productId: knoData.id
    }).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        knoData.collect = knoData.collect - 1
        knoData.isCollect = false;
        let item = 'dataList[' + index + ']';
        this.setData({
          [item]: knoData,
        })
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '操作失败',
        icon: "none"
      })
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = app.globalData.userId || ""
    let path = "/featurePackage/pages/knowledgeArea/knowledgeArea?isShare=1" + "&userId=" + userId
    return {
      title: app.globalData.commonShareTitle,
      path: path
    }
  }
})